package com.ht.api.call.func.impl.fan;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.util.HtUtil;
import com.ht.api.service.FanService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * 接粉组绑定与解绑
 * @author asq
 * @createTime 2025年4月2日 15:54:43
 */
@Slf4j
public class FanTeamRelFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "接粉组绑定与解绑";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();
		StreamLoadConfig streamLoadConfig = me.getStreamLoadConfig();

		// 验证参数
		HtUtil.checkParam(param, "team_id", "add", "ids");
		List<String> ids = param.getJSONArray("ids").toList(String.class);
		if (ids.isEmpty()) {
			throw new HtException("ids不能为空~");
		}

		// 查询
		String fanTeamId = param.getStr("team_id");
		Entity fanTeam = Db.createSqlParser("fan_team").selectFilter("relation_cnt,normal_relation_cnt,normal_cnt").findById(ds, fanTeamId);
		if (fanTeam == null) {
			throw new HtException("数据不存在~");
		}

		// 判断绑定或解绑
		int add = param.getInt("add");
		if (add == 0) {
			bind(ds, streamLoadConfig, fanTeam, ids);
		} else {
			unbind(ds, streamLoadConfig, fanTeam, ids);
		}

		return null;
	}

	private void bind(DataSource ds, StreamLoadConfig slconfog, Entity fanTeam, List<String> ids) {
		// 最终要保存的数据集合
		List<Entity> dbList = new ArrayList<>();
		
		// 查询旧的关联数据
		int teamType = fanTeam.getInt("team_type");
		List<String> oldBandIds = new ArrayList<>();
		DbList relList = null;
		if (teamType == 1) {
			relList = Db.createSqlParser("fan_service_team_relation").select("userid rel")
					.where("team_id", fanTeam.getMainId()).where("status", 0).query(ds);
		} else if (teamType == 2) {
			relList = Db.createSqlParser("fan_chat_team_relation").select("chat_id rel")
					.where("team_id", fanTeam.getMainId()).where("status", 0).query(ds);
		} else if (teamType == 3) {
			relList = Db.createSqlParser("fan_user_team_relation").select("userid rel")
					.where("team_id", fanTeam.getMainId()).where("status", 0).query(ds);
		} else if (teamType == 4) {
			relList = Db.createSqlParser("fan_official_user_team_relation").select("userid rel")
					.where("team_id", fanTeam.getMainId()).where("status", 0).query(ds);
		}
		relList.stream().forEach(bean -> {
			oldBandIds.add(bean.getStr("rel"));
		});

		ids.removeAll(oldBandIds);

		// 更新正常状态下的广告位的配置信息
		if (teamType == 1 || teamType == 2) {
			List<String> bandIds = new ArrayList<>();
			bandIds.addAll(ids);
			bandIds.addAll(oldBandIds);
			updatePositionConfig(ds, fanTeam.getStr("appid"), fanTeam.getMainId(), bandIds);
		}

		String time = DateUtil.now();

		// 新增关联表
		ids.stream().forEach(rel -> {
			if (teamType == 1) {
				Entity fanServiceTeamRelation = Db.createEntity("fan_service_team_relation");
				fanServiceTeamRelation.set("team_id", fanTeam.getMainId());
				fanServiceTeamRelation.set("userid", rel);
				fanServiceTeamRelation.set("status", 0);
				fanServiceTeamRelation.set("last_update_time", time);
				fanServiceTeamRelation.set("last_relation_time", time);
				fanServiceTeamRelation.set("first_relation_time", time);
				dbList.add(fanServiceTeamRelation);

				HtUtil.createLog(ds, fanServiceTeamRelation.getMainId(), "绑定了[" + fanTeam.getStr("name") + "]");

			} else if (teamType == 2) {
				Entity fanChatTeamRelation = Db.createEntity("fan_chat_team_relation");
				fanChatTeamRelation.set("team_id", fanTeam.getMainId());
				fanChatTeamRelation.set("chat_id", rel);
				fanChatTeamRelation.set("status", 0);
				fanChatTeamRelation.set("last_update_time", time);
				fanChatTeamRelation.set("last_relation_time", time);
				fanChatTeamRelation.set("first_relation_time", time);

				dbList.add(fanChatTeamRelation);
				HtUtil.createLog(ds, fanChatTeamRelation.getMainId(), "绑定了[" + fanTeam.getStr("name") + "]");
			} else if (teamType == 3) {
				Entity fanChatTeamRelation = Db.createEntity("fan_user_team_relation");
				fanChatTeamRelation.set("team_id", fanTeam.getMainId());
				fanChatTeamRelation.set("userid", rel);
				fanChatTeamRelation.set("status", 0);
				fanChatTeamRelation.set("last_update_time", time);
				fanChatTeamRelation.set("last_relation_time", time);
				fanChatTeamRelation.set("first_relation_time", time);

				dbList.add(fanChatTeamRelation);
				HtUtil.createLog(ds, fanChatTeamRelation.getMainId(), "绑定了[" + fanTeam.getStr("name") + "]");
			} else if (teamType == 4) {
				Entity fanChatTeamRelation = Db.createEntity("fan_official_user_team_relation");
				fanChatTeamRelation.set("team_id", fanTeam.getMainId());
				fanChatTeamRelation.set("userid", rel);
				fanChatTeamRelation.set("status", 0);
				fanChatTeamRelation.set("last_update_time", time);
				fanChatTeamRelation.set("last_relation_time", time);
				fanChatTeamRelation.set("first_relation_time", time);

				dbList.add(fanChatTeamRelation);
				HtUtil.createLog(ds, fanChatTeamRelation.getMainId(), "绑定了[" + fanTeam.getStr("name") + "]");
			}
		});
		
		// 接粉组主表数据维护
		fanTeam.set("normal_cnt", ids.size());
		dbList.add(fanTeam);

		// 批量写入数据库
		Db.insertBatchWithStream(slconfog, dbList);
	}

	private void unbind(DataSource ds, StreamLoadConfig slconfog, Entity fanTeam, List<String> ids) {
		// 最终要保存的数据集合
		List<Entity> dbList = new ArrayList<>();
		
		// 查询旧的关联数据
		int teamType = fanTeam.getInt("team_type");
		boolean isUserRel = teamType == 1;
		List<String> unbandIds = new ArrayList<>();
		List<String> bandIds = new ArrayList<>();
		DbList relList = null;

		if (teamType == 1) {
			relList = Db.createSqlParser("fan_service_team_relation").select("userid rel")
					.where("team_id", fanTeam.getMainId()).query(ds);
		} else if (teamType == 2) {
			relList = Db.createSqlParser("fan_chat_team_relation").select("chat_id rel")
					.where("team_id", fanTeam.getMainId()).query(ds);
		} else if (teamType == 3) {
			relList = Db.createSqlParser("fan_user_team_relation").select("userid rel")
					.where("team_id", fanTeam.getMainId()).query(ds);
		} else if (teamType == 4) {
			relList = Db.createSqlParser("fan_official_user_team_relation").select("userid rel")
					.where("team_id", fanTeam.getMainId()).query(ds);
		}
		relList.stream().forEach(bean -> {
			if (bean.getInt("status") == 1) {
				unbandIds.add(bean.getStr("rel"));
			} else {
				bandIds.add(bean.getStr("rel"));
			}
		});

		ids.removeAll(unbandIds);

		if (ids.size() == relList.size()) {
			long normalPositionCount = Db.createSqlParser("position_channel")
					.where("team_id", fanTeam.getMainId()).where("status", 1).count(ds);

			if (normalPositionCount > 0) {
				throw new HtException("已有广告位在使用中，不能全部解绑！");
			}
		}

		// 更新正常状态下的广告位的配置信息
		if (teamType == 1 || teamType == 2) {
			bandIds.removeAll(ids);
			updatePositionConfig(ds, fanTeam.getStr("appid"), fanTeam.getMainId(), bandIds);
		}


		String time = DateUtil.now();

		// 新增关联表
		ids.stream().forEach(rel -> {
			if (isUserRel) {
				Entity fanServiceTeamRelation = Db.createEntity("fan_service_team_relation");
				fanServiceTeamRelation.set("team_id", fanTeam.getMainId());
				fanServiceTeamRelation.set("userid", rel);
				fanServiceTeamRelation.set("status", 1);
				fanServiceTeamRelation.set("last_update_time", time);
				fanServiceTeamRelation.set("last_relation_time", time);
				fanServiceTeamRelation.set("first_relation_time", time);
				dbList.add(fanServiceTeamRelation);

				HtUtil.createLog(ds, fanServiceTeamRelation.getMainId(), "解绑了[" + fanTeam.getStr("name") + "]");
			} else {
				Entity fanChatTeamRelation = Db.createEntity("fan_chat_team_relation");
				fanChatTeamRelation.set("team_id", fanTeam.getMainId());
				fanChatTeamRelation.set("chat_id", rel);
				fanChatTeamRelation.set("status", 1);
				fanChatTeamRelation.set("last_update_time", time);
				fanChatTeamRelation.set("last_relation_time", time);
				fanChatTeamRelation.set("first_relation_time", time);
				dbList.add(fanChatTeamRelation);
				HtUtil.createLog(ds, fanChatTeamRelation.getMainId(), "解绑了[" + fanTeam.getStr("name") + "]");
			}


		});

		// 新增关联表
		ids.stream().forEach(rel -> {
			if (teamType == 1) {
				Entity fanServiceTeamRelation = Db.createEntity("fan_service_team_relation");
				fanServiceTeamRelation.set("team_id", fanTeam.getMainId());
				fanServiceTeamRelation.set("userid", rel);
				fanServiceTeamRelation.set("status", 1);
				fanServiceTeamRelation.set("last_update_time", time);
				fanServiceTeamRelation.set("last_relation_time", time);
				fanServiceTeamRelation.set("first_relation_time", time);
				dbList.add(fanServiceTeamRelation);

				HtUtil.createLog(ds, fanServiceTeamRelation.getMainId(), "解绑了[" + fanTeam.getStr("name") + "]");

			} else if (teamType == 2) {
				Entity fanChatTeamRelation = Db.createEntity("fan_chat_team_relation");
				fanChatTeamRelation.set("team_id", fanTeam.getMainId());
				fanChatTeamRelation.set("chat_id", rel);
				fanChatTeamRelation.set("status", 1);
				fanChatTeamRelation.set("last_update_time", time);
				fanChatTeamRelation.set("last_relation_time", time);
				fanChatTeamRelation.set("first_relation_time", time);

				dbList.add(fanChatTeamRelation);
				HtUtil.createLog(ds, fanChatTeamRelation.getMainId(), "解绑了[" + fanTeam.getStr("name") + "]");
			} else if (teamType == 3) {
				Entity fanChatTeamRelation = Db.createEntity("fan_user_team_relation");
				fanChatTeamRelation.set("team_id", fanTeam.getMainId());
				fanChatTeamRelation.set("userid", rel);
				fanChatTeamRelation.set("status", 1);
				fanChatTeamRelation.set("last_update_time", time);
				fanChatTeamRelation.set("last_relation_time", time);
				fanChatTeamRelation.set("first_relation_time", time);

				dbList.add(fanChatTeamRelation);
				HtUtil.createLog(ds, fanChatTeamRelation.getMainId(), "解绑了[" + fanTeam.getStr("name") + "]");
			} else if (teamType == 4) {
				Entity fanChatTeamRelation = Db.createEntity("fan_official_user_team_relation");
				fanChatTeamRelation.set("team_id", fanTeam.getMainId());
				fanChatTeamRelation.set("userid", rel);
				fanChatTeamRelation.set("status", 1);
				fanChatTeamRelation.set("last_update_time", time);
				fanChatTeamRelation.set("last_relation_time", time);
				fanChatTeamRelation.set("first_relation_time", time);

				dbList.add(fanChatTeamRelation);
				HtUtil.createLog(ds, fanChatTeamRelation.getMainId(), "解绑了[" + fanTeam.getStr("name") + "]");
			}
		});
		
		// 接粉组主表数据维护
		fanTeam.set("normal_cnt", -ids.size());
		dbList.add(fanTeam);

		// 批量写入数据库
		Db.insertBatchWithStream(slconfog, dbList);
	}

	public void updatePositionConfig (DataSource ds, String appid, String fanTeamId, List<String> ids) {
		DbList positionList = Db.createSqlParser("position_channel")
				.where("team_id", fanTeamId).where("status", 1).query(ds);

		for (Entity position : positionList) {
			log.info("绑定或解绑时，更新外部数据");
			FanService.edit(ds, appid, position.getMainId(), position.getStr("name"), 
					position.getStr("state"), position.getStr("in_type"), ids);
		}

	}



}
